package com.bit.forum.service;

import com.bit.forum.common.AppResult;
import com.bit.forum.common.ResultCode;
import com.bit.forum.dao.ArticleMapper;
import com.bit.forum.exception.ApplicationException;
import com.bit.forum.model.Article;
import com.bit.forum.model.Board;
import com.bit.forum.model.User;
import com.bit.forum.utils.StringUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Resource
    private IUserService userService;
    @Resource
    private IBoardService boardService;
    @Resource
    private ArticleMapper articleMapper;

    @Override
    public Article selectById(Long id) {
        // 非空校验
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 调用DAO
        Article article = articleMapper.selectByPrimaryKey(id);
        // 返回结果
        return article;
    }

    @Override
    @Transactional
    public void create(Article article) {
        //非空校验
        if(article==null||article.getBoardId()==null||article.getUserId()==null||
                StringUtil.isEmpty(article.getContent())||StringUtil.isEmpty(article.getTitle())){
            log.info(ResultCode.ERROR_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_ARTICLE_NOT_EXISTS));
        }
        //设置默认值
        article.setReplyCount(0);//回复数
        article.setLikeCount(0);//点赞数
        article.setVisitCount(0);//访问数
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
        //写入数据库
        int row = articleMapper.insertSelective(article);
        if(row<=0){
            log.info(ResultCode.ERROR_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_ARTICLE_NOT_EXISTS));
        }
        //获取用户信息
        User user=userService.selectByPrimaryKey(article.getUserId());
        if(user==null){
            log.warn(ResultCode.FAILED.toString()+"用户:"+article.getUserId()+"发帖失败");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        //更新用户发帖数量
         userService.addOneArticleCountById(user.getId());

        //获取板块信息
        Board board=boardService.selectById(article.getBoardId());
        if(board==null){
            log.warn(ResultCode.FAILED.toString()+"板块:"+article.getBoardId()+"发帖失败");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        //更新板块发帖数
        boardService.addOneArticleCountById(board.getId());
        //打印日志
        log.info(ResultCode.SUCCESS.toString()+"user id:"+user.getId()+"board id:"+board.getId()
        +"article id:"+article.getId()+"发帖成功");

    }

    @Override
    public List<Article> selectAll() {
        List<Article> articles = articleMapper.selectAll();
        return articles;
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        // 非空校验
        if (boardId == null || boardId <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 校验版块是否存在
        Board board = boardService.selectById(boardId);
        if (board == null) {
            // 打印日志
            log.warn(ResultCode.ERROR_BOARD_NOT_EXISTS.toString() + ", board id = " + boardId);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_BOARD_NOT_EXISTS));
        }
        // 调用DAO，查询
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);
        // 返回结果
        return articles;
    }

    @Override
    public Article selectDetailById(Long id) {
        if(id==null||id<=0){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        Article article = articleMapper.selectDetailById(id);
        if(article==null){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setVisitCount(article.getVisitCount()+1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //article.setVisitCount(article.getVisitCount()+1);
        return article;
    }

    @Override
    public void modify(Long id, String title, String content) {
        if(id==null||id<=0||StringUtil.isEmpty(title)||StringUtil.isEmpty(content)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        updateArticle.setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void thumbsUpById(Long id) {
        if(id==null||id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article==null||article.getDeleteState()==1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
       if(article.getState()==1){
           log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
           throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
       }
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setLikeCount(article.getLikeCount()+1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
    }

    @Transactional
    // 事务管理
    @Override
    public void deleteById(Long id) {
        if(id==null||id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 根据Id查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article==null||article.getDeleteState()==1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString() + ", article id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte)1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新板块帖子数量
        boardService.subOneArticleCountById(article.getBoardId());
        //更新用户文章数量
        userService.subOneArticleCountById(article.getUserId());
        log.info("删除帖子成功, article id = " + article.getId() + ", user id = " + article.getUserId() + ".");
    }
}
